package com.tjetc.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tjetc.common.JsonResult;
import com.tjetc.common.JwtTokenUtil;
import com.tjetc.dao.CaregiverInfoMapper;
import com.tjetc.dao.ElderInfoMapper;
import com.tjetc.dao.PhyExamMapper;
import com.tjetc.dao.RelativeInfoMapper;
import com.tjetc.entity.*;
import com.tjetc.service.PhyExamService;
import com.tjetc.service.RelativeInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class RelativeInfoServiceImpl implements RelativeInfoService {
    @Value("${token.expiration}")
    private int tokeExpiraton;
    @Autowired
    private RelativeInfoMapper relativeInfoMapper;
    @Autowired
    private ElderInfoMapper elderInfoMapper;
    @Override
    public JsonResult findById(Long id) {
        RelativeInfo relativeInfo=relativeInfoMapper.selectById(id);
        ElderInfo elderInfo=elderInfoMapper.selectById(relativeInfo.getElderlyId());
        relativeInfo.setElderInfo(elderInfo);
        return JsonResult.success(relativeInfo);
    }
    @Override
    public   JsonResult findNamePage(String name, Integer pageNo, Integer pageSize){
        //设置页码和每页数量
        Page<RelativeInfo> page=Page.of(pageNo,pageSize);
        //把adminPage传入mapper查询中，adminPage就是最后的分页结果
        Page<RelativeInfo>relativeInfoPage= relativeInfoMapper.selectPageLikeName(page,name);
        for (RelativeInfo relativeInfo : relativeInfoPage.getRecords()) {
            ElderInfo elderInfo=elderInfoMapper.selectById(relativeInfo.getElderlyId());
            relativeInfo.setElderInfo(elderInfo);
        }
        //convert方法转换Page中 records集合元素类型 Admin---->AdminView
        //new Function<Admin,AdminView>(){};表示创建一个实现Function的匿名类 对象
        return JsonResult.success(relativeInfoPage);
    }
    @Override
    public JsonResult deleteById(Long id) {
        int rows=relativeInfoMapper.deleteById(id);
        if (rows>0){
            return JsonResult.success("删除成功");
        }
        else {
            return JsonResult.fail("删除失败");
        }
    }
    @Override
    public JsonResult login(String username, String password){
        //如果任何一个为空，都返回true
        if (StringUtils.isAnyBlank(username,password)){
            return JsonResult.fail("用户名或者密码不能为空");
        }
        //根据用户名和密码查询Admin
        RelativeInfo relativeInfo=relativeInfoMapper.selectByUsernameAndPassword(username,password);
        if (relativeInfo==null){
            return JsonResult.fail("用户名或者密码错误");
        }else {
            //用户名或者密码正确,生成token
            Map<String,Object> claims=new HashMap<>();
            claims.put("userId",relativeInfo.getFamilyId());
            String token= JwtTokenUtil.generateToken(claims,"user",tokeExpiraton);
            return JsonResult.success(token,relativeInfo);
        }
    }
    @Override
    public JsonResult register(String username, String password, String phonenumber) {
        LocalDateTime now=LocalDateTime.now();
        //如果任何一个为空，都返回true
        if (StringUtils.isAnyBlank(username,password)){
            return JsonResult.fail("用户名或者密码不能为空");
        }
        if (StringUtils.isAnyBlank(phonenumber)){
            return JsonResult.fail("电话号码不能为空");
        }
        //根据用户名和密码查询Admin
        RelativeInfo user1=relativeInfoMapper.selectByUsername(username);
        RelativeInfo user2=new RelativeInfo();
        if (user1!=null){
            return JsonResult.fail("该用户名已注册");
        }else {
            user2.setUsername(username);
            user2.setPassword(password);
            user2.setPhonenumber(phonenumber);
            user2.setCreateTime(now);
            user2.setUpdateTime(now);
            relativeInfoMapper.insert(user2);
            return JsonResult.success("注册成功",null);
        }
    }
    //@Transactional用在service方法上，保证事务
    //注意：默认情况@Transactional只对运行时异常起作用(RuntimeException)
    @Transactional
    @Override
    public JsonResult save(RelativeInfo relativeInfoParam) {
        RelativeInfo relativeInfo=null;
        LocalDateTime now=LocalDateTime.now();
        //通过判断id值有无判断是新增还是更新，id值无是新增，id值有就是更新
        if(relativeInfoParam.getFamilyId()==null||relativeInfoParam.getFamilyId()<=0){
            //新增
            relativeInfo=new RelativeInfo();
            BeanUtils.copyProperties(relativeInfoParam,relativeInfo);
            relativeInfo.setCreateTime(now);
            relativeInfo.setUpdateTime(now);
            relativeInfoMapper.insert(relativeInfo);
            return JsonResult.success("新增成功",null);
        }else{
            //更新
            //根据id查询Admin信息
            relativeInfo=relativeInfoMapper.selectById(relativeInfoParam.getFamilyId());
            if(relativeInfo==null){
                return JsonResult.fail("用户不存在，更新失败");
            }
            //要更新的字段
            relativeInfo.setUpdateTime(now);
            relativeInfo.setElderInfo(relativeInfo.getElderInfo());
            relativeInfo.setName(relativeInfoParam.getName());
            relativeInfo.setIsDeleted(relativeInfoParam.getIsDeleted());
            relativeInfo.setElderlyId(relativeInfoParam.getElderlyId());
            relativeInfo.setIsEmergency(relativeInfoParam.getIsEmergency());
            relativeInfo.setPhonenumber(relativeInfoParam.getPhonenumber());
            relativeInfo.setRelationship(relativeInfoParam.getRelationship());
            int rows=relativeInfoMapper.updateById(relativeInfo);
            if (rows>0){
                return JsonResult.success("更新成功",null);
            }else {
                return JsonResult.fail("用户不存在，更新失败");
            }
        }
    }
}
